Python Send Email

  1. Open SMTP service for your email and obtain the SMTP password.

  2. Create a Python script

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    import win32serviceutil
    import win32service
    import win32event
    import servicemanager
    import smtplib
    import time
    import re
    import sys
    import urllib2

    class Getmyip:
    def visit(self,url):
    opener = urllib2.urlopen(url)
    if url == opener.geturl():
    IPstr = opener.read()
    return re.search('\d+\.\d+\.\d+\.\d+',IPstr).group(0)

    def getip(self):
    myip = self.visit("http://www.net.cn/static/customercare/yourip.asp")
    return myip

    class AppServerSvc (win32serviceutil.ServiceFramework):
    _svc_name_ = "TestService"
    _svc_display_name_ = "Test Service"

    def __init__(self,args):
    win32serviceutil.ServiceFramework.__init__(self,args)
    self.hWaitStop = win32event.CreateEvent(None,0,0,None)
    self.run = True

    def SvcStop(self):
    self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
    win32event.SetEvent(self.hWaitStop)
    self.run = False

    def SvcDoRun(self):
    while(self.run==True):
    self.main()

    def main(self):
    fromaddr = 'XXX@qq.com'
    toaddrs = 'XXX@qq.com'

    server = smtplib.SMTP_SSL('smtp.qq.com')
    server.set_debuglevel(1)
    print("--- Need Authentication ---")
    username = 'XXX'
    password = 'XXX'
    server.login(username, password)

    prev_msg = ''

    while(True):
    getmyip=Getmyip()
    msg = getmyip.getip()
    if not msg==prev_msg:
    server.sendmail(fromaddr, toaddrs, msg)
    prev_msg = msg
    time.sleep(10)

    server.quit()

    if __name__ == '__main__':
    if len(sys.argv) == 1:
    servicemanager.Initialize()
    servicemanager.PrepareToHostSingle(AppServerSvc)
    servicemanager.StartServiceCtrlDispatcher()
    else:
    win32serviceutil.HandleCommandLine(AppServerSvc)
  3. Make python file into an exe

    1
    pyinstaller -F MyService.py
  4. Make exe into a Windows service

    1
    2
    3
    4
    sc create MyServer binPath=$exe_path
    sc start MyServer
    sc stop MyServer
    sc delete MyServer